package m2;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.List;

public class Producer {
    static String[] msgs = {
            "15103111039,创建",
            "15103111065,创建",
            "15103111039,付款",
            "15103117235,创建",
            "15103111065,付款",
            "15103117235,付款",
            "15103111065,完成",
            "15103111039,推送",
            "15103117235,完成",
            "15103111039,完成"
    };

    public static void main(String[] args) throws Exception {
        //创建生产者
        DefaultMQProducer p = new DefaultMQProducer("producer-group-2");
        //指定nameserver
        p.setNamesrvAddr("192.168.64.141:9876");
        //启动
        p.start();

        //遍历msgs数组发送消息，通过“队列选择器”选择一个固定队列
        for (String s:msgs) {
            // 15103111065,完成 -->  ["15103111065",  "完成"]
            String[] a = s.split(",");
            Long orderId = Long.valueOf(a[0]);

            Message msg = new Message("Topic2", s.getBytes());
            // p.send(msg, 队列选择器, 用来选择队列的数据会被传递到队列选择器中进行运算)
            SendResult r =
                    p.send(msg, new MessageQueueSelector() {
                        @Override
                        public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                            // mqs 参数是队列列表，从列表中要选择一个队列返回
                            Long orderId = (Long) arg;
                            int index = (int) (orderId % mqs.size());

                            return mqs.get(index);
                        }
                    }, orderId);

            System.out.println("消息已发送:"+r);
        }

        p.shutdown();
    }
}